<template>
  <Dialog v-model="superVisible" :title="title" width="800px" class="knowledge-form-dialog">
    <div class="form-container">
      <!-- 表单头部 -->
      <div class="form-header">
        <div class="header-icon">
          <Icon :icon="superForm.id ? 'ep:edit' : 'ep:plus'" />
        </div>
        <div class="header-content">
          <h3 class="form-title">{{ title }}</h3>
          <p class="form-subtitle">{{ superForm.id ? '编辑知识库信息' : '创建新的知识库条目' }}</p>
        </div>
      </div>

      <!-- 表单内容 -->
      <div class="form-content">
        <el-form
          ref="superFormRef"
          :model="superForm"
          :rules="rules"
          label-width="120px"
          class="knowledge-form"
        >
          <!-- 基本信息 -->
          <div class="form-section">
            <div class="section-header">
              <Icon icon="ep:document" class="section-icon" />
              <span class="section-title">基本信息</span>
            </div>

            <div class="form-grid">
              <el-form-item label="标题" prop="title" class="form-item items-start">
                <el-input
                  v-model="superForm.title"
                  placeholder="请输入知识标题"
                  class="enhanced-input"
                >
                  <template #prefix>
                    <Icon icon="ep:document" />
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item label="问题类型" prop="knowledgeType" class="form-item">
                <el-radio-group v-model="superForm.knowledgeType" class="type-radio-group">
                  <div class="radio-wrapper">
                    <el-radio :label="1" class="type-radio">
                      <div class="radio-content">
                        <Icon icon="ep:document" class="radio-icon" />
                        <span>一般业务</span>
                      </div>
                    </el-radio>
                  </div>
                  <div class="radio-wrapper">
                    <el-radio :label="2" class="type-radio">
                      <div class="radio-content">
                        <Icon icon="ep:warning" class="radio-icon" />
                        <span>业务问题</span>
                      </div>
                    </el-radio>
                  </div>
                </el-radio-group>
              </el-form-item>
            </div>

            <el-form-item label="标签名称" prop="labelName" class="form-item">
              <el-input
                v-model="superForm.labelName"
                placeholder="请输入标签名称"
                class="enhanced-input"
              >
                <template #prefix>
                  <Icon icon="ep:price-tag" />
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="关键词" prop="keys" class="form-item">
              <el-input
                v-model="superForm.keys"
                type="textarea"
                :rows="3"
                placeholder="请输入关键词，多个关键词用逗号分隔"
                class="enhanced-textarea"
              />
              <div class="form-tip">
                <Icon icon="ep:info-filled" class="tip-icon" />
                <span>多个关键词请用英文逗号分隔，如：客服,服务,帮助</span>
              </div>
            </el-form-item>

            <el-form-item label="问法" prop="ask" class="form-item">
              <el-input v-model="superForm.ask" placeholder="请输入常见问法" class="enhanced-input">
                <template #prefix>
                  <Icon icon="ep:chat-dot-round" />
                </template>
              </el-input>
            </el-form-item>
          </div>

          <!-- 回答配置 -->
          <div class="form-section">
            <div class="section-header">
              <Icon icon="ep:setting" class="section-icon" />
              <span class="section-title">回答配置</span>
            </div>

            <div class="form-grid">
              <el-form-item label="问答方式" prop="answerType" class="form-item">
                <el-radio-group v-model="superForm.answerType" class="answer-radio-group">
                  <div class="radio-wrapper">
                    <el-radio :label="1" class="answer-radio">
                      <div class="radio-content">
                        <Icon icon="ep:chat-line-round" class="radio-icon" />
                        <span>单句回答</span>
                      </div>
                    </el-radio>
                  </div>
                  <div class="radio-wrapper">
                    <el-radio :label="2" class="answer-radio">
                      <div class="radio-content">
                        <Icon icon="ep:chat-dot-square" class="radio-icon" />
                        <span>多轮回答</span>
                      </div>
                    </el-radio>
                  </div>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="跳转方式" prop="jumpType" class="form-item items-start">
                <el-select
                  v-model="superForm.jumpType"
                  placeholder="请选择跳转方式"
                  class="enhanced-select"
                >
                  <template #prefix>
                    <Icon icon="ep:switch" />
                  </template>
                  <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                  >
                    <div class="option-content">
                      <Icon :icon="getJumpIcon(item.id)" class="option-icon" />
                      <span>{{ item.label }}</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
          </div>

          <!-- 播放设置 -->
          <div class="form-section">
            <div class="section-header">
              <Icon icon="ep:video-play" class="section-icon" />
              <span class="section-title">播放设置</span>
            </div>

            <el-form-item label="忽略无声" prop="ignoreSilence" class="form-item">
              <el-radio-group v-model="superForm.ignoreSilence" class="silence-radio-group">
                <div class="radio-wrapper">
                  <el-radio :label="0" class="silence-radio">
                    <div class="radio-content">
                      <Icon icon="ep:circle-close" class="radio-icon" />
                      <span>未选</span>
                    </div>
                  </el-radio>
                </div>
                <div class="radio-wrapper">
                  <el-radio :label="1" class="silence-radio">
                    <div class="radio-content">
                      <Icon icon="ep:mute" class="radio-icon" />
                      <span>忽略</span>
                    </div>
                  </el-radio>
                </div>
                <div class="radio-wrapper">
                  <el-radio :label="2" class="silence-radio">
                    <div class="radio-content">
                      <Icon icon="ep:video-play" class="radio-icon" />
                      <span>跟随主流程一起播放</span>
                    </div>
                  </el-radio>
                </div>
              </el-radio-group>
            </el-form-item>

            <div class="form-grid">
              <el-form-item label="是否重复播放" prop="enableContinuousPlay" class="form-item">
                <el-radio-group v-model="superForm.enableContinuousPlay" class="repeat-radio-group">
                  <div class="radio-wrapper">
                    <el-radio :label="0" class="repeat-radio">
                      <div class="radio-content">
                        <Icon icon="ep:close" class="radio-icon" />
                        <span>不重复</span>
                      </div>
                    </el-radio>
                  </div>
                  <div class="radio-wrapper">
                    <el-radio :label="1" class="repeat-radio">
                      <div class="radio-content">
                        <Icon icon="ep:refresh" class="radio-icon" />
                        <span>重复</span>
                      </div>
                    </el-radio>
                  </div>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="播放次数" prop="continuousPlayNum" class="form-item items-start">
                <el-input-number
                  v-model="superForm.continuousPlayNum"
                  :min="0"
                  :max="100"
                  placeholder="请输入播放次数"
                  class="enhanced-number"
                />
              </el-form-item>
            </div>
          </div>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="superVisible = false" class="cancel-btn">
          <Icon icon="ep:close" class="btn-icon" />
          取消
        </el-button>
        <el-button
          type="primary"
          :disabled="fromDisable"
          :loading="fromDisable"
          @click="submit"
          class="submit-btn"
        >
          <Icon icon="ep:check" class="btn-icon" />
          {{ fromDisable ? '保存中...' : '确定' }}
        </el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup>
import * as defaultIvrKnowApi from '@/api/call/manage'

defineOptions({ name: 'KnowledgeForm' })

// 响应式数据
const superVisible = ref(false)
const title = ref('知识库问题')
const fromDisable = ref(false)
const superFormRef = ref()

const superForm = reactive({
  id: '',
  flowId: 0,
  title: '',
  knowledgeType: '',
  labelName: '',
  keys: '',
  ask: '',
  answerType: '',
  jumpType: '',
  ignoreSilence: '',
  enableContinuousPlay: '',
  continuousPlayNum: ''
})

const options = [
  { label: '挂机', id: 1 },
  { label: '等待用户应答', id: 2 },
  { label: '下一个主流程', id: 3 },
  { label: '指定主动流程', id: 4 },
  { label: '转人工', id: 5 }
]

const rules = reactive({
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  knowledgeType: [{ required: true, message: '问题类型不能为空', trigger: 'change' }],
  labelName: [{ required: true, message: '标签名称不能为空', trigger: 'blur' }],
  keys: [{ required: true, message: '关键词不能为空', trigger: 'blur' }],
  ask: [{ required: true, message: '问法不能为空', trigger: 'blur' }],
  answerType: [{ required: true, message: '问答方式不能为空', trigger: 'change' }],
  jumpType: [{ required: true, message: '跳转方式不能为空', trigger: 'change' }],
  ignoreSilence: [{ required: true, message: '忽略无声不能为空', trigger: 'change' }],
  enableContinuousPlay: [{ required: true, message: '是否重复播放不能为空', trigger: 'change' }],
  continuousPlayNum: [{ required: true, message: '播放次数不能为空', trigger: 'blur' }]
})

const emit = defineEmits(['success'])

// 获取跳转图标
const getJumpIcon = (id) => {
  const iconMap = {
    1: 'ep:phone',
    2: 'ep:timer',
    3: 'ep:right',
    4: 'ep:share',
    5: 'ep:user'
  }
  return iconMap[id] || 'ep:switch'
}

// 打开弹窗
const open = (type, idVal) => {
  superVisible.value = true
  if (idVal) {
    title.value = '编辑知识库问题'
    getDetail(idVal)
  } else {
    superForm.id = ''
    title.value = '创建知识库问题'
    resetForm()
  }
}

// 获取详情
const getDetail = async (idVal) => {
  try {
    const data = await defaultIvrKnowApi.getIvrknowDetail(idVal)
    Object.assign(superForm, {
      id: data.id,
      title: data.title,
      knowledgeType: data.knowledgeType,
      labelName: data.labelName,
      keys: data.keys,
      ask: data.ask,
      answerType: data.answerType,
      jumpType: data.jumpType,
      ignoreSilence: data.ignoreSilence,
      enableContinuousPlay: data.enableContinuousPlay,
      continuousPlayNum: data.continuousPlayNum
    })
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(superForm, {
    title: '',
    knowledgeType: '',
    labelName: '',
    keys: '',
    ask: '',
    answerType: '',
    jumpType: '',
    ignoreSilence: '',
    enableContinuousPlay: '',
    continuousPlayNum: ''
  })

  // 重置表单验证
  nextTick(() => {
    superFormRef.value?.clearValidate()
  })
}

// 提交表单
const submit = async () => {
  try {
    await superFormRef.value.validate()
    fromDisable.value = true

    if (superForm.id) {
      await defaultIvrKnowApi.updateIvrknow(superForm)
      ElMessage.success('更新成功')
    } else {
      await defaultIvrKnowApi.createIvrknow(superForm)
      ElMessage.success('创建成功')
    }

    superVisible.value = false
    emit('success')
  } catch (error) {
    console.error('提交失败:', error)
    if (error !== 'validation failed') {
      ElMessage.error('操作失败，请重试')
    }
  } finally {
    fromDisable.value = false
  }
}

defineExpose({ open })
</script>

<style lang="scss" scoped>
.knowledge-form-dialog {
  :deep(.el-dialog) {
    border-radius: 16px;
    overflow: hidden;
  }

  :deep(.el-dialog__header) {
    background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
    color: white;
    padding: 20px 24px;
  }

  :deep(.el-dialog__title) {
    color: white;
    font-weight: 600;
    font-size: 18px;
  }

  :deep(.el-dialog__headerbtn .el-dialog__close) {
    color: white;
    font-size: 18px;
  }

  :deep(.el-dialog__body) {
    padding: 0;
  }

  :deep(.el-dialog__footer) {
    padding: 0;
  }
}

.form-container {
  background: #f8fafc;
}

/* 表单头部 */
.form-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 24px;
  background: white;
  border-bottom: 1px solid rgba(0, 82, 204, 0.1);
}

.header-icon {
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.header-content {
  flex: 1;
}

.form-title {
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 4px 0;
}

.form-subtitle {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

/* 表单内容 */
.form-content {
  padding: 24px;
  max-height: 600px;
  overflow-y: auto;
}

.knowledge-form {
  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #374151;
  }

  :deep(.el-form-item__error) {
    font-size: 12px;
  }
}

/* 表单区块 */
.form-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid rgba(0, 82, 204, 0.1);
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid rgba(0, 82, 204, 0.1);
}

.section-icon {
  color: #0052cc;
  font-size: 18px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;

  @media (max-width: 768px) {
    grid-template-columns: 1fr;
  }
}

.form-item {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

/* 输入框样式 */
.enhanced-input,
.enhanced-select,
.enhanced-number {
  :deep(.el-input__wrapper) {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.2s ease;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
    }

    &.is-focus {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.2);
    }
  }
}

.enhanced-textarea {
  :deep(.el-textarea__inner) {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.2s ease;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
    }

    &:focus {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.2);
    }
  }
}

.form-tip {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 8px;
  font-size: 12px;
  color: #6b7280;
}

.tip-icon {
  color: #0052cc;
  font-size: 14px;
}

/* 修复单选框组样式 */
.type-radio-group,
.answer-radio-group,
.silence-radio-group,
.repeat-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.radio-wrapper {
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: white;

  &:hover {
    border-color: #0052cc;
    background: rgba(0, 82, 204, 0.02);
  }

  &:has(.el-radio.is-checked) {
    border-color: #0052cc;
    background: rgba(0, 82, 204, 0.05);
  }
}

.type-radio,
.answer-radio,
.silence-radio,
.repeat-radio {
  margin: 0;

  :deep(.el-radio__input) {
    display: none;
  }

  :deep(.el-radio__label) {
    padding: 0;
  }
}

.radio-content {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  transition: color 0.2s ease;
}

.radio-icon {
  font-size: 16px;
  color: #6b7280;
  transition: color 0.2s ease;
}

/* 选中状态样式 */
.radio-wrapper:has(.el-radio.is-checked) {
  .radio-content {
    color: #0052cc;
  }

  .radio-icon {
    color: #0052cc;
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .type-radio-group,
  .answer-radio-group,
  .silence-radio-group,
  .repeat-radio-group {
    flex-direction: column;
  }

  .radio-wrapper {
    width: 100%;
  }
}

/* 选择框选项样式 */
.option-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.option-icon {
  font-size: 14px;
  color: #6b7280;
}

/* 底部按钮 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 24px;
  background: white;
  border-top: 1px solid rgba(0, 82, 204, 0.1);
}

.cancel-btn {
  border: 2px solid #e5e7eb;
  color: #6b7280;
  border-radius: 8px;
  padding: 10px 20px;

  &:hover {
    border-color: #d1d5db;
    color: #374151;
  }

  .btn-icon {
    margin-right: 6px;
  }
}

.submit-btn {
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  border: none;
  border-radius: 8px;
  padding: 10px 20px;

  &:hover:not(:disabled) {
    background: linear-gradient(135deg, #1d4ed8 0%, #1e40af 100%);
  }

  &:disabled {
    background: #9ca3af;
    cursor: not-allowed;
  }

  .btn-icon {
    margin-right: 6px;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .knowledge-form-dialog {
    :deep(.el-dialog) {
      width: 95% !important;
      margin: 20px auto;
    }
  }

  .form-header {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }

  .form-content {
    padding: 16px;
  }

  .form-section {
    padding: 16px;
  }

  .type-radio-group,
  .answer-radio-group,
  .silence-radio-group,
  .repeat-radio-group {
    flex-direction: column;
  }

  .dialog-footer {
    flex-direction: column;
    gap: 8px;
  }

  .cancel-btn,
  .submit-btn {
    width: 100%;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .form-container {
    background: #1f2937;
  }

  .form-section {
    background: #374151;
    border-color: rgba(255, 255, 255, 0.1);
  }

  .form-title {
    color: #f9fafb;
  }

  .form-subtitle {
    color: #d1d5db;
  }

  .section-title {
    color: #f9fafb;
  }

  .radio-content {
    color: #e5e7eb;
  }

  .type-radio,
  .answer-radio,
  .silence-radio,
  .repeat-radio {
    background: #4b5563;
    border-color: rgba(255, 255, 255, 0.1);
  }
}
</style>
